package oakclub.service;

import oakclub.global.Config;
import oakclub.global.Container;
import oakclub.utility.HttpUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class ActivityService
{
    private final String backendUrl = Config.get("server.backend.url");
    private final Logger logger = LoggerFactory.getLogger(ActivityService.class);

    private final String SECRET_BACKEND_CCU = "0928340929bcb242c629c96f17b6e3ce";
    private final String ROUTE_PING = "ccu/api/ping";

    public void setOnline(long userId)
    {
        // set online
        try
        {
            MemcachedService memecachedService = (MemcachedService) Container.getComponent(MemcachedService.class);
            memecachedService.set(MemcachedService.Key.ONLINE, userId, 1);
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }

        // ping to backend to calculate ccu
        try
        {
            HashMap<String, String> params = new HashMap<>();
            params.put("secret_key", this.SECRET_BACKEND_CCU);
            params.put("user_id", String.valueOf(userId));
            HttpUtility.sendPost(this.backendUrl+'/'+this.ROUTE_PING, params);
        }
        catch(Exception e)
        {
            this.logger.warn("http issue", e);
        }
    }

    public boolean isOnline(long userId)
    {
        try
        {
            MemcachedService memecachedService = (MemcachedService) Container.getComponent(MemcachedService.class);
            return memecachedService.get(MemcachedService.Key.ONLINE, userId) != null;
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }
        return false;
    }
}
